/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FindResourcesPanel.java
 *
 * Created on Sep 9, 2010, 10:49:31 PM
 */

package org.dafe.partyband.gui.songs;

import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.AbstractListModel;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dafe.partyband.db.api.ISong;
import org.dafe.partyband.importer.api.IDirectoryScanner;
import org.dafe.partyband.importer.api.IImporterServices;
import org.openide.DialogDescriptor;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;

/**
 *
 * @author dafe
 */
public class FindResourcesPanel extends javax.swing.JPanel {
    private static final String FIND_RES_DIR = "findResDir";

    private static final IImporterServices importerServices = Lookup.getDefault().lookup(IImporterServices.class);
    private static final IDirectoryScanner dirScanner = importerServices.getDirectoryScanner();

    private static final ExecutorService EXEC = Executors.newSingleThreadExecutor();

    private final ISong song;
    private final MaterialsModel materialsModel;
    private final JComponent dlgParent;
    private final Color origForeground;
    private DialogDescriptor dd;

    /** Creates new form FindResourcesPanel */
    public FindResourcesPanel(ISong song, JComponent dlgParent) {
        initComponents();
        this.song = song;
        this.dlgParent = dlgParent;

        dirScanner.setEncoder(importerServices.getNameEncoder());

        searchInProgressLabel.setVisible(false);

        materialsModel = new MaterialsModel();
        materialsList.setModel(materialsModel);
        materialsList.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                checkMaterialSelection();
            }

        });

        origForeground = dirTextField.getForeground();
        dirTextField.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                checkDir();
            }

            public void removeUpdate(DocumentEvent e) {
                checkDir();
            }

            public void changedUpdate(DocumentEvent e) {
                checkDir();
            }

        });
        String resDirPath = NbPreferences.forModule(FindResourcesPanel.class).get(FIND_RES_DIR, null);
        if (resDirPath != null) {
            dirTextField.setText(resDirPath);
        }

        checkDir();
        checkMaterialSelection();
    }

    void attachDialogDescriptor(DialogDescriptor dd) {
        this.dd = dd;
        checkMaterialSelection();
    }

    private void checkDir() {
        File file = new File(dirTextField.getText());
        if (file.isDirectory() && file.exists()) {
            dirTextField.setForeground(origForeground);
            searchButton.setEnabled(true);
        } else {
            dirTextField.setForeground(Color.red);
            searchButton.setEnabled(false);
        }
    }

    private void checkMaterialSelection() {
        if (dd != null) {
            dd.setValid(materialsList.getSelectedIndex() != -1);
        }
    }

    public List<File> getMaterials () {
        int[] selIndices = materialsList.getSelectedIndices();
        List<File> result = new ArrayList<File>();
        for (int i = 0; i < selIndices.length; i++) {
            result.add(materialsModel.getFileAt(selIndices[i]));
        }
        return result;
    }

    private class MaterialsModel extends AbstractListModel {
        private List<File> files;

        void setContent (List<File> files) {
            this.files = files;
            fireContentsChanged(this, 0, files.size() - 1);
        }

        File getFileAt(int index) {
            return files != null ? files.get(index) : null;
        }

        public int getSize() {
            return files != null ? files.size() : 0;
        }

        public Object getElementAt(int index) {
            return files != null ? files.get(index).getName() : null;
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        dirTextField = new javax.swing.JTextField();
        chooseDirButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        materialsList = new org.jdesktop.swingx.JXList();
        searchInProgressLabel = new org.jdesktop.swingx.JXBusyLabel();

        jLabel1.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.jLabel1.text",new Object[] {})); // NOI18N
        jLabel1.setToolTipText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.jLabel1.toolTipText",new Object[] {})); // NOI18N

        dirTextField.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.dirTextField.text",new Object[] {})); // NOI18N
        dirTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dirTextFieldActionPerformed(evt);
            }
        });

        chooseDirButton.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.chooseDirButton.text",new Object[] {})); // NOI18N
        chooseDirButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chooseDirButtonActionPerformed(evt);
            }
        });

        jLabel2.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.jLabel2.text",new Object[] {})); // NOI18N

        searchButton.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.searchButton.text",new Object[] {})); // NOI18N
        searchButton.setToolTipText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.searchButton.toolTipText",new Object[] {})); // NOI18N
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(materialsList);

        searchInProgressLabel.setText(org.openide.util.NbBundle.getMessage(FindResourcesPanel.class, "FindResourcesPanel.searchInProgressLabel.text",new Object[] {})); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dirTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                            .addComponent(searchInProgressLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(searchButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(chooseDirButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(dirTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chooseDirButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(searchInProgressLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void dirTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dirTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dirTextFieldActionPerformed

    private void chooseDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseDirButtonActionPerformed
        File curDir = new File(dirTextField.getText());
        JFileChooser fileChooser = curDir.exists() ? new JFileChooser(curDir) : new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setDialogTitle(NbBundle.getMessage(FindResourcesPanel.class, "LBL_FindResDirTitle"));
        int resultOption = fileChooser.showDialog(SwingUtilities.getWindowAncestor(dlgParent),
                NbBundle.getMessage(FindResourcesPanel.class, "LBL_ChooseResDir"));

        if (resultOption == JFileChooser.APPROVE_OPTION) {
            File dir = fileChooser.getSelectedFile();
            dirTextField.setText(dir.getPath());
            NbPreferences.forModule(FindResourcesPanel.class).put(FIND_RES_DIR, dir.getPath());
        }
    }//GEN-LAST:event_chooseDirButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        searchInProgress(true);
        dirScanner.setDirectory(new File(dirTextField.getText()));
        
        EXEC.execute(new Runnable() {
            public void run() {
                final List<File> foundMaterials = dirScanner.findSimilar(song.getName());
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        materialsModel.setContent(foundMaterials);
                        materialsList.setSelectionInterval(0, foundMaterials.size() - 1);
                        searchInProgress(false);
                    }
                });
            }
        });

    }//GEN-LAST:event_searchButtonActionPerformed

    private void searchInProgress (boolean inProgress) {
        dirTextField.setEnabled(!inProgress);
        chooseDirButton.setEnabled(!inProgress);
        searchInProgressLabel.setVisible(inProgress);
        searchInProgressLabel.setBusy(inProgress);
        materialsList.setEnabled(!inProgress);
        searchButton.setEnabled(!inProgress);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton chooseDirButton;
    private javax.swing.JTextField dirTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXList materialsList;
    private javax.swing.JButton searchButton;
    private org.jdesktop.swingx.JXBusyLabel searchInProgressLabel;
    // End of variables declaration//GEN-END:variables

}
